#include "settings.h"
#include "globals.h"
#include "ui_settings.h"
#include <QSettings>
#include <QMessageBox>

Settings::Settings(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Settings)
{
    ui->setupUi(this);
    ui->dbHostEdit->setText(dbHost);
    ui->dbNameEdit->setText(dbName);
    ui->dbNamePortSpinBox->setValue(dbPort);
    ui->dbUserEdit->setText(dbUser);
    ui->dbPasswordEdit->setText(dbPassword);
    if ( dbDriver.compare("QMYSQL") == 0)
        ui->mysqlDriverRadio->setChecked(true);
    else if ( dbDriver.compare("QSQLITE") == 0 )
        ui->sqliteDriverRadio->setChecked(true);
    else
    {
        ui->sqliteDriverRadio->setChecked(false);
        ui->mysqlDriverRadio->setChecked(false);
    }
}

Settings::~Settings()
{
    delete ui;
}

void Settings::on_buttonBox_accepted()
{
    QSettings setCheck(QCoreApplication::organizationName(),
                       QCoreApplication::applicationName());
    if( ui->mysqlDriverRadio->isChecked() )
        setCheck.setValue("database/driver","QMYSQL");
    else if ( ui->sqliteDriverRadio->isChecked() )
        setCheck.setValue("database/driver", "QSQLITE");
    else
        QMessageBox::critical(this, tr("Settings can't be saved"), tr("WhiteKnight can't connect to database whithout database driver"));

    if (!ui->dbHostEdit->text().isEmpty())
        setCheck.setValue("database/host", ui->dbHostEdit->text());
    else
        QMessageBox::critical(this,
                              tr("Settings can't be saved"),
                              tr("WhiteKnight can't connect to database whithout database, please enter correct host name or IP"));

    if (!ui->dbUserEdit->text().isEmpty())
        setCheck.setValue("database/user", ui->dbUserEdit->text());
    else
        QMessageBox::critical(this,
                              tr("Settings can't be saved"),
                              tr("WhiteKnight can't authorize to database without username"));

    if (!ui->dbPasswordEdit->text().isEmpty())
        setCheck.setValue("database/password", ui->dbPasswordEdit->text());
    else
        QMessageBox::critical(this,
                              tr("Settings can't be saved"),
                              tr("WhiteKnight can't authorize to database withour user password"));

    if (ui->dbNamePortSpinBox->value() > 1000 )
        setCheck.setValue("database/port", ui->dbNamePortSpinBox->value());
    else
        QMessageBox::critical(this,
                              tr("Settings can't be saved"),
                              tr("WhiteKnight can't connect to database without any port"));

    if (!ui->dbNameEdit->text().isEmpty())
        setCheck.setValue("database/name", ui->dbNameEdit->text());
    else
        QMessageBox::critical(this,
                              tr("Settings can't be saved"),
                              tr("WhiteKnight can't use database, beacuse database name isn't specified"));
}
